import React, { Component, useRef, useEffect, useState } from "react";
import { Button, Input, Row, Space, Table, Popover, Switch, message } from 'antd';
import { CmdbContent, CmdbHeader , TempImportModal, HcpTableTooltip, HcpTable } from "@/components";
import cmdbres from "@/data/cmdbres";
import request from "@/utils/request";
import hcpUtils from "@/utils/hcpUtils";
import CreateRule from "./createRule";
import DeleteRule from "./deleteRule";
import ExecuteRule from "./executeRule";
import AutoExecute from "./autoExecute";
import '../index.less';

const user = hcpUtils.getUser();

const ModelRelationRules = ({ history}) => {
    const [searchValue, setSearchValue] = useState();
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [row, setRow] = useState([]);
    const [showCreateRule, setShowCreateRule] = useState(false);
    const [showDeleteRule, setShowDeleteRule] = useState(false);
    const [showExecuteRule, setShowExecuteRule] = useState(false);
    const [showAutoExecute,  setShowAutoExecute] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    
    const changeRule = async (record) => {
        try {
            if(record.autoExecutionSwitch == 0)  {
                setRow(record);
                setShowAutoExecute(true);
                return;
            }
            const res = await request({
                ...cmdbres.autoExecuteModuleAssociateRule(record.ruleId, 0, user.staffName),
                data: {}
            });
            if (res && res.code == 200) {
                message.success("自动执行变更成功！");
                getTableData();
            }
        } catch (error) {
            console.log('changeRule -> error', error);
        }
    };

    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryModuleAssociateRules,
                data: {
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                    queryFilter:{
                        LIKE:{
                            ruleName: searchValue ? searchValue: undefined
                        }
                    }
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total, 
                }));
                res.data.map((item, index) => item.key=index);
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        } 
    };

    useEffect(() => {
        getTableData();
    }, []);

    const handleTableChange = (e) => {
        getTableData(e);
    };
    
    const columns = [
        {
            title: "规则序号",
            key: "ruleId",
            dataIndex: "ruleId",
            isShow: true,
            width: 80,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => (
                <HcpTableTooltip
                    label="ID"
                    showValue={record.ruleId}
                />
            )  
        },
        {
            title: "规则名称",
            key: "ruleName",
            dataIndex: "ruleName",
            isShow: true,
            width: 100,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "模型关联名称",
            key: "moduleAssociateName",
            dataIndex: "moduleAssociateName",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "模型关联条件",
            key: "conditions",
            dataIndex: "conditions",
            isShow: true,
            width: 160,
            render: (text, record, index) => {
                const {srcModuleName, destModuleName} = record;
                let str = "";
                text?.map((item, i) => {
                    str += `${srcModuleName}[${item.srcModulePropertyName || item.srcModuleAssociateKey}] ${item.associateCondition} ${destModuleName}[${item.destModulePropertyName||item.destModuleAssociateKey}]`;
                    if(i!= text.length -1) {
                        str += ";"
                    }
                })
                return str || '-';
            }
        },
        {
            title: "Cron表达式",
            key: "actionCron",
            dataIndex: "actionCron",
            isShow: true,
            width: 100,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "描述",
            key: "description",
            dataIndex: "description",
            isShow: true,
            width: 100,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "执行状态",
            key: "autoExecutionSwitch",
            dataIndex: "autoExecutionSwitch",
            isShow: true,
            width: 100,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => {
                return (
                    <Switch 
                        checkedChildren="ON" 
                        unCheckedChildren="OFF" 
                        checked={text}
                        onChange={()=> {changeRule(record)}}
                    />
                )
            }
        },
        {
            title: "操作",
            // fixed: 'right',
            width: 80,
            woIsSystem: 1,
            woIsHidden: 1,
            render: (text, record, index) => {
                return (
                <Space key={record.ruleId}>
                    <Popover content="执行">
                        <span
                            className="iconfont icon-restart-new"
                            onClick={() => { setRow(record); setShowExecuteRule(true); }}
                        />
                    </Popover>
                    {/* <Popover content="编辑">
                        <span
                            className="iconfont icon-edit"
                            onClick={() => { setRow(record); setShowCreateRule(true); }}
                        />
                    </Popover> */}
                    <Popover content="删除">
                        <span 
                            className="iconfont icon-delete" 
                            onClick={() => { setRow(record); setShowDeleteRule(true); }}
                        />
                    </Popover>
                </Space>
                )
            }
        } 
    ]

    return (
        <CmdbContent>
            <CmdbHeader title={"关联规则"} />
            <section className="hcp__page">
                <section className="hcp__page__container">
                    <div className="back-white m-b-10 padding-10">
                        规则名称：
                        <Input
                            placeholder="请输入关键字搜索"
                            value={searchValue}
                            onChange={(e) => {
                                setSearchValue(e.target.value);
                            }}
                            style={{ width: "210px" }}
                            allowClear
                        />
                        <Space style={{marginLeft: 10}}>
                            <Button type="primary" onClick={()=> {getTableData()}}>查询</Button>
                            <Button onClick={() => {setSearchValue();}}>重置</Button>
                        </Space>
                    </div>
                    <div className="back-white padding-10">
                        <Space className="m-b-10">
                            <Button type="primary" onClick={() => {setRow();setShowCreateRule(true);}}>
                                新建规则
                            </Button>
                        </Space>
                        <p>规则数量 | {pagination.total}个</p>
                        <HcpTable
                            columns={columns}
                            loading={loading}
                            dataSource={tableData}
                            scroll={{ x: '100%' }}
                            pagination={{
                                showSizeChanger: true,
                                showQuickJumper: {
                                goButton: (
                                    <Button style={{ margin: "0 10px" }}>确定</Button>
                                ),
                                },
                                ...pagination,
                            }}
                            onChange={handleTableChange}
                            hideSetting
                        />
                    </div>
                </section>
            </section>
            {showCreateRule&&<CreateRule
                onCreateFinish={getTableData}
                visible={showCreateRule}
                setVisible={setShowCreateRule}
                info={row}
            />}
            <DeleteRule
                onDeleteFinish={getTableData}
                visible={showDeleteRule}
                setVisible={setShowDeleteRule}
                info={row}
            />
            <ExecuteRule
                onDeleteFinish={getTableData}
                visible={showExecuteRule}
                setVisible={setShowExecuteRule}
                info={row}
            />
            {showAutoExecute  && <AutoExecute 
                onCreateFinish={getTableData}
                visible={showAutoExecute}
                setVisible={setShowAutoExecute}
                info={row}
            />}
        </CmdbContent>
    );
};

export default ModelRelationRules;